package top.i51213.fastaction.action.print;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import top.i51213.fastaction.action.pdf.PdfUtil;
import top.i51213.fastaction.uri.UriReader;

public class ImagePrintDocumentAdapter extends PrintDocumentAdapter {
    private Context context;
    private List<Uri> list;
    private String taskName;

    public ImagePrintDocumentAdapter(Context context, List<Uri> list, String taskName) {
        this.context = context;
        this.list = list;
        this.taskName = taskName;
    }

    PrintAttributes.MediaSize mediaSize;
    PrintAttributes.Margins margins;

    @Override
    public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes,//
                         CancellationSignal cancellationSignal,//
                         LayoutResultCallback callback, Bundle extras) {
        // Respond to cancellation request
        if (cancellationSignal.isCanceled()) {
            callback.onLayoutCancelled();
            return;
        }
        mediaSize = newAttributes.getMediaSize();
        margins = newAttributes.getMinMargins();
        //System.out.println(mediaSize.toString());
        //System.out.println(margins.toString());
        int pages = list.size();
        if (pages > 0) {
            // Return print information to print framework
            PrintDocumentInfo info = new PrintDocumentInfo
                    .Builder(taskName + ".pdf")
                    .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                    .setPageCount(pages).build();
            // Content layout reflow is complete
            callback.onLayoutFinished(info, true);
        } else {
            // Otherwise report an error to the print framework
            callback.onLayoutFailed("Page count calculation failed.");
        }
    }

    @Override
    public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, //
                        CancellationSignal cancellationSignal, //
                        WriteResultCallback callback) {
        try {
            Document document = new Document(new RectangleReadOnly((float) (mediaSize.getWidthMils() / 1000.0 * 72), (float) (mediaSize.getHeightMils() / 1000.0 * 72)));
            document.setMargins((float) (margins.getLeftMils() / 1000.0 * 72), (float) (margins.getRightMils() / 1000.0 * 72),
                    (float) (margins.getTopMils() / 1000.0 * 72), (float) (margins.getBottomMils() / 1000.0 * 72));

            // File file = new File(context.getExternalCacheDir(), "temp.pdf");
            // FileOutputStream fos = new FileOutputStream(file);
            Rectangle rectangle = document.getPageSize();

            OutputStream fos = new BufferedOutputStream(new FileOutputStream(destination.getFileDescriptor()));
            PdfWriter writer = PdfWriter.getInstance(document, fos);
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
            document.open();
            for (Uri uri : list) {

                if (cancellationSignal.isCanceled()) {
                    callback.onWriteCancelled();
                    System.out.println("打印取消");
                    document.close();
                    return;
                }
                UriReader uriReader = new UriReader(context, uri);
                InputStream inputStream = uriReader.openAutoCloseInputStream();
                byte[] data = PdfUtil.readImageData(inputStream);
                inputStream.close();
                Image image = Image.getInstance(data);

                //System.out.println(uri);
                float dw = rectangle.getWidth() - document.leftMargin() - document.rightMargin();
                float dh = rectangle.getHeight() - document.topMargin() - document.bottomMargin();

                float iw = image.getScaledWidth();
                float ih = image.getScaledHeight();
                //System.out.println("w:" + image.getScaledWidth() + " h:" + image.getScaledHeight());
                if (iw != ih) {
                    if ((dw > dh) ^ (iw > ih)) {
                        //image.setRotation(90);
                        image.setRotationDegrees(90);
                    }
                }
                //System.out.println("w:" + image.getScaledWidth() + " h:" + image.getScaledHeight());
                float nw, nh;
                iw = image.getScaledWidth();
                ih = image.getScaledHeight();
                if (ih * dw > dh * iw) {//图片过高
                    nw = iw * dh / ih;//乘以放缩比
                    nh = dh;
                } else {
                    nw = dw;
                    nh = ih * dw / iw;
                }
                PdfUtil.scaleToFit(image, nw, nh);
                float left = (float) (margins.getLeftMils() / 1000.0 * 72);
                float bottom = (float) (margins.getBottomMils() / 1000.0 * 72);
                image.setAbsolutePosition(left + (dw - nw) / 2, bottom + (dh - nh) / 2);
                document.newPage();
                document.add(image);
            }
            document.close();
            callback.onWriteFinished(new PageRange[]{new PageRange(0, list.size() - 1)});
        } catch (Exception | Error e) {
            e.printStackTrace();
            callback.onWriteFailed(e.toString());
        }
    }

    @Override
    public void onFinish() {
        super.onFinish();
    }

}
